package com.kgc.dao.impl;

import java.sql.*;

public class BaseDao {

    Connection conn;

    PreparedStatement pstmt;

    ResultSet rs;

    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","ok");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    ResultSet getResultSet(String sql,Object[] args){
        conn = this.getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            if(args != null){
                for(int i = 0;i < args.length;i++){
                    pstmt.setObject(i + 1,args[i]);
                }
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }


    int executeUpdate(String sql,Object[] args){
        conn = this.getConnection();
        int count = 0;
        try {
            pstmt = conn.prepareStatement(sql);
            if(args != null){
                for(int i = 0;i < args.length;i++){
                    pstmt.setObject(i + 1,args[i]);
                }
            }
            count = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeAll();
        }
        return count;
    }


    void closeAll(){
        try {
            if(rs != null){
                rs.close();
            }
            if(pstmt != null){
                pstmt.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}
